package com.pay.wx;


import common.ClientUtils;
import common.WXPayUtils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信转账信息
 */
public class WXTransfers {

    private WXConfig config;

    public WXTransfers(WXConfig config) throws Exception {

        this.config = config;
        WXPayUtils.checkWXPayConfig(config);
    }

    /**
     * 微信企业打款到零钱
     *
     * @param partner_trade_no 商户流水号
     * @param openid           用户openid
     * @param amount           金额 （单位分）
     * @param desc             说明
     * @param check_name       是否校验真实姓名
     * @param re_user_name     真实姓名  如果校验，需填写真实姓名
     * @return
     * @throws Exception
     */
    public Map<String, String> promotionTransfers(String partner_trade_no, String openid,
                                                  Integer amount, String desc,
                                                  boolean check_name,
                                                  String re_user_name) throws Exception {
        Map<String, String> param = new HashMap<>();
        param.put("mch_appid", config.getAppID());
        param.put("mchid", config.getMchID());
        param.put("nonce_str", WXPayUtils.generateNonceStr());
        param.put("partner_trade_no", partner_trade_no);
        param.put("openid", openid);
        if (check_name) {
            param.put("check_name", "FORCE_CHECK");
            if (re_user_name != null) {
                param.put("re_user_name", re_user_name);
            } else {
                throw new Exception("需校验用户真姓名,请填写用户真实姓名");
            }
        } else {
            param.put("check_name", "NO_CHECK");
        }
        param.put("amount", amount.toString());
        param.put("desc", desc);
        String signature = WXPayUtils.generateSignature(param, config.getKey());
        param.put("sign", signature);
        String paramXml = WXPayUtils.mapToXml(param);
        return ClientUtils.certPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",
                paramXml,
                config.getMchID(),
                config.getCertStream());
    }
}
